import * as vscode from "vscode";
import * as path from "path";
import { CommandId } from "@ap/command";
import { getPackageJson } from "../packageJson";
import { PackageConfig } from "src/types/config";
import {
  mapLish,
  getBox3MapList,
  setIsMapLish,
  isMapLish,
} from "@ap/user/map/getMapList";
let codeLenses: vscode.CodeLens[] = [];
export class dao3CfgProvider implements vscode.CodeLensProvider {
  public async provideCodeLenses(
    document: vscode.TextDocument,
    token: vscode.CancellationToken,
  ): Promise<vscode.CodeLens[]> {
    codeLenses = [];
    let dao3CfgJson = JSON.parse(document.getText());
    let output = dao3CfgJson.ArenaPro.map ?? {};
    findPatternInText(
      new RegExp(/(?:"map"\s*:\s*\{)([\s\S]*)(\})/),
      createsMapCodeLens,
      document,
      output,
    );
    output = dao3CfgJson.ArenaPro.outputAndUpdate[0] ?? "bundle.js";
    findPatternInText(
      new RegExp(/(?:"outputAndUpdate"\s*:\s*\[)([\s\S]*)(\])/),
      createsOutputAndUpdateCodeLens,
      document,
      output,
    );
    return codeLenses;
  }
}

async function findPatternInText(
  pattern: RegExp,
  createCodeLensFunction: (
    line: vscode.TextLine,
    output: string | Record<string, any>,
  ) => void,
  document: vscode.TextDocument,
  output: string | Record<string, any>,
) {
  let text = document.getText();
  let regex = new RegExp(pattern);
  let matches;

  if ((matches = regex.exec(text)) !== null) {
    const line = document.lineAt(document.positionAt(matches.index).line);
    createCodeLensFunction(line, output);
  }
}

async function createsMapCodeLens(
  line: vscode.TextLine,
  output: string | Record<string, any>,
) {
  let mapJson = output as Record<string, any>;
  let data1 = await getMapByEditHashAndId(mapJson);
  let title1 = "扩展地图链接";
  let tooltip1 = "获取该神岛账号下的扩展地图";
  if (data1) {
    title1 = "扩展地图：" + data1.name;
    tooltip1 = data1.detail ?? "";
  }
  let command1 = {
    title: "$(extensions-editor-label-icon) " + title1,
    command: CommandId.file_mapTool,
    tooltip: tooltip1,
  };
  let command2 = {
    title: "$(symbol-class) 一键同步地图资源",
    command: CommandId.map_resource,
    tooltip: "同步扩展地图中[模型/音频/图片]资源，并写入类型声明文件及代码片段",
  };
  let command3 = {
    title: "$(breakpoints-view-icon) 打开创作端",
    command: CommandId.map_showMap,
  };
  codeLenses.push(new vscode.CodeLens(line.range, command1));
  if (mapJson.id) {
    codeLenses.push(new vscode.CodeLens(line.range, command2));
    codeLenses.push(new vscode.CodeLens(line.range, command3));
  }
}

async function getMapByEditHashAndId(packageJson: Record<string, any>) {
  const editHash = packageJson.editHash;
  const id = Number(packageJson.id);
  if (editHash && id) {
    if (!mapLish && !isMapLish) {
      setIsMapLish(true);
      await getBox3MapList();
    }
    let data;
    for (const item of mapLish) {
      data = item.subMaps.find(
        (item) => item.editHash === editHash && item.id === id,
      );
      if (data) {
        data["detail"] = item.detail;
        return data;
      }
    }
    return;
  }
}

function createsOutputAndUpdateCodeLens(
  line: vscode.TextLine,
  output: string | Record<string, any>,
) {
  if (typeof output === "object") {
    output = output.name;
  }
  let command1 = {
    title: ("$(output) 完整编译输出文件名：" + output) as string,
    command: CommandId.file_outputName,
    tooltip:
      "选择输出列表下的指定值，用于指定完整编译后的文件名，如有入口配置会优先选择当前入口文件",
  };
  codeLenses.push(new vscode.CodeLens(line.range, command1));
}
